/**
 * @Time 2019-7-12 13:57:21
 * SQLite数据库操作
 * @URL http://www.html5plus.org/doc/zh_cn/sqlite.html
 * @权限 需要在manifest中添加SQLite权限
 */
var SQLiteDB = {
	DBName: 'MyAPPDb',
	DBPath: '_doc/Database.db',
	init: function() {
		if (window.plus) {
			mui.plusReady(function() {
				setTimeout(function() {
					var ws = plus.webview.currentWebview();
					ws.addEventListener('close', function() { //窗口关闭时，关闭数据库
						SQLiteDB.closeDatabase();
						console.log('webview close---closeDatabase');
					});
				}, 200);
			})
		}
	},
	openDB: function(success, fail) { //打开数据库
		if (!SQLiteDB.isOpenDatabase()) {
			plus.sqlite.openDatabase({
				name: SQLiteDB.DBName,
				path: SQLiteDB.DBPath,
				success: function(e) {
					console.log('openDatabase success!');
					if (success)
						success(e)
				},
				fail: function(e) {
					console.log('openDatabase failed: ' + JSON.stringify(e));
					if (fail)
						fail(e)
				}
			});
		} else {
			console.log('Database already open!');
			if (success)
				success()
		}
	},
	isOpenDatabase: function() { //检查数据库是否打开
		var options = {
			name: SQLiteDB.DBName,
			path: SQLiteDB.DBPath
		}
		return plus.sqlite.isOpenDatabase(options);
	},
	closeDatabase: function(success, fail) { //关闭数据库
		if (SQLiteDB.isOpenDatabase()) {
			var options = {
				name: SQLiteDB.DBName,
				success: success,
				fail: fail,
			}
			plus.sqlite.closeDatabase(options);
		} else {
			if (success)
				success()
		}
	},
	/**
	 * @param {Object} operation  需要执行的事务操作 begin（开始事务）、commit（提交）、rollback（回滚）。
	 */
	transaction: function(operation, success, fail) {
		var options = {
			name: SQLiteDB.DBName,
			operation: operation,
			success: success,
			fail: fail,
		}
		plus.sqlite.transaction(options);
	},
	transactionBegin: function(success, fail) { //开启事务
		SQLiteDB.transaction("begin", success, fail);
	},
	transactionCommit: function(success, fail) { //提交事务
		SQLiteDB.transaction("commit", success, fail);
	},
	transactionRollback: function(success, fail) { //回滚事务
		SQLiteDB.transaction("rollback", success, fail);
	},
	_exec: function(sql, success, fail) {
		plus.sqlite.executeSql({
			name: SQLiteDB.DBName,
			sql: sql,
			success,
			fail
		})
	},
	executeSQL: function(sql, useTran, success, fail, noclose) { //执行语句
		SQLiteDB.openDB(
			function() { //打开成功
				exec();
			},
			function(e) { //打开失败
				mui.alert("数据库打开失败");
				if (fail)
					fail(e);
			});

		function exec() {
			if (useTran) { //使用事务
				SQLiteDB.transactionBegin(function() {
					SQLiteDB._exec(
						sql,
						function(data) {
							if (success) //执行回调
								success(data);
							SQLiteDB.transactionCommit();
							if (!noclose)
								SQLiteDB.closeDatabase();
						},
						function(e) {
							if (fail) //执行回调
								fail(e);
							SQLiteDB.transactionRollback();
							if (!noclose)
								SQLiteDB.closeDatabase();
						}
					)
				});
			} else { //不使用事务
				//console.log(sql)
				SQLiteDB._exec(
					sql,
					function(data) {
						//console.log('Execute Sql success')
						if (success) //执行回调
							success(data);
						if (!noclose)
							SQLiteDB.closeDatabase();
					},
					function(e) {
						//console.log('Execute Sql fail')
						if (fail) //执行回调
							fail(e);
						if (!noclose)
							SQLiteDB.closeDatabase();
					}
				)
			}
		}
	},
	selectSQL: function(sql, success, fail) {
		SQLiteDB.openDB(
			function() { //打开成功
				plus.sqlite.selectSql({
					name: SQLiteDB.DBName,
					sql: sql,
					success: function(data) {
						if (success)
							success(data)
					},
					fail: function(e) {
						if (fail)
							fail(e);
					}
				});
			},
			function(e) { //打开失败
				mui.alert("数据库打开失败");
				if (fail)
					fail(e);
			});
		
	},
	insertData: function(tableName, tbdata, success, fail) { //插入
		SQLiteDB.openDB(
			function() { //打开成功
				SQLiteDB.createTbSql(tableName, tbdata,
					function() { //创建表成功
						SQLiteDB.insertTbSql(tableName, tbdata, success, fail);
					},
					function() { //创建表失败
						if (fail)
							fail(e);
					});
			},
			function(e) { //打开失败
				if (fail)
					fail(e);
			});
	},
	insertTbSql: function(tbname, listData, success, fail) { //插入
		if (listData.length > 0) {
			for (var i = 0; i < listData.length; i++) {
				var insertSql = "";
				var textcl = "";
				var valuel = "";
				var jcList = [];
				for (var ls in listData[i]) {
					var tName = JSON.stringify(ls).replace('"', "'").replace('"', "'");

					if (textcl == "") {
						textcl += tName;
						valuel += "'" + listData[i][ls] + "'";
					} else {
						textcl += "," + tName;
						valuel += ",'" + listData[i][ls] + "'";
					}
				}

				if (textcl != "") {
					insertSql = "insert into " + tbname + " (" + textcl + ") values (" + valuel + ")";
					SQLiteDB.executeSQL(insertSql, false, success, fail, true);
				}
			}
		}
	},
	createTbSql: function(tbname, listData, success, fail) { //创建表
		var tbsql = "";
		if (listData.length > 0) {
			for (var ls in listData[0]) {
				var tName = JSON.stringify(ls).replace('"', "'").replace('"', "'");
				if (tbsql == "") {
					tbsql += tName + " text null ";
				} else {
					tbsql += "," + tName + " text null ";
				}
			}
		}
		if (tbsql != "") {
			tbsql = "create table if not exists " + tbname + " (" + tbsql + ")"
			SQLiteDB.executeSQL(tbsql, false, success, fail);
		}
	},
	dropTable:function(tbname, success, fail){  //删除表
		var sql = 'drop table if exists  ' + tbname;
		SQLiteDB.executeSQL(sql, false, success, fail);
	},
	clearTable:function(tbname, success, fail){  //清空表
		var sql = 'DELETE FROM ' + tbname;
		SQLiteDB.executeSQL(sql, false, success, fail);
	}
};

export default SQLiteDB
